#include <memory>
#include <vector>
#include "udpServer.hpp"
#include "terminal.hpp"
using namespace std;

Log lg;
void Usage(const std::string& cmd)
{
    cout << "\n\r" << cmd << " port[1024+]" << endl << endl; 
}

// 1.执行命令返回
void execCommond(int sockfd, const string& ip, uint16_t port, const string &cmd)
{
    sockaddr_in client;
    client.sin_addr.s_addr = inet_addr(ip.c_str());
    client.sin_family = AF_INET;
    client.sin_port = htons(port);
    socklen_t len = sizeof(client);
    vector<string> errcmd = 
    {
        "rm",
        "mv",
        "cp",
        "kill"
    };
    for(const auto& e : errcmd)
    {
        if(cmd.find(e) != string::npos)
        {
            lg(Warning, "%s-%hd is execute a err cmd", ip.c_str(), port);
            string err = "a err cmd";
            sendto(sockfd, err.c_str(), err.size(), 0, (const sockaddr *)&client, len);
            return;
        }
    }
    FILE* pf = popen(cmd.c_str(), "r");
    string response;
    char buffer[1024];
    while(fgets(buffer, 1024, pf) != nullptr)
    {
        response += buffer;
    }

    
    sendto(sockfd, response.c_str(), response.size(), 0, (const sockaddr *)&client, len);
}

OnlineUser online;
// 2.聊天室
void chatRoom(int sockfd, const string& ip, uint16_t port, const string &message)
{
    string name = ip + "-" + to_string(port);
    if(message == "online") 
    {
        online.addUser(ip, port);
        lg(Info, "%s is online", name.c_str());
        return;
    }
    if(message == "quit")
    {
        online.delUser(ip, port);
        lg(Info, "%s is quit", name.c_str());
        return;
    }
    
    sockaddr_in client;
    socklen_t len = sizeof(client);
    bzero(&client, sizeof client);
    client.sin_family = AF_INET;
    client.sin_addr.s_addr = inet_addr(ip.c_str());
    client.sin_port = htons(port);

    string response;
    if(online.isOnline(ip, port))
    {
        response = "[" + name + "]# " + message;
        online.broadCast(sockfd, ip, port, response);
    }
    else
    {
        response = "你还没有上线, 请输入online上线";
        sendto(sockfd, response.c_str(), response.size(), 0, (sockaddr *)&client, len);
    }
    
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    uint16_t port = stoi(argv[1]);
    unique_ptr<UdpServer> up(new UdpServer(chatRoom, port));
    up->init();
    up->run();
    return 0;   
}